/*
 * Copyright (c) 2017 zhangcm. All Rights Reserved.
 */
package com.jnzc.ocr.tool.zuul.filter;

import com.jnzc.ocr.common.consts.error.SystemErrorConsts;
import com.jnzc.ocr.common.utils.JsonUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SEND_ERROR_FILTER_ORDER;

/**
 * @author zhangcm
 * @version 1.0, 2017/10/7
 */
@Component
public class ErrorFilter extends ZuulFilter {

    private final Logger logger = LoggerFactory.getLogger(ErrorFilter.class);

    @Override
    public String filterType() {
        return FilterConstants.ERROR_TYPE;
    }

    @Override
    public int filterOrder() {
        return SEND_ERROR_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext context = RequestContext.getCurrentContext();
        context.setSendZuulResponse(false);
        context.setResponseStatusCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
        context.setResponseBody(JsonUtils.toJson(SystemErrorConsts.ERROR));
        context.getResponse().setContentType("application/json;charset=UTF-8");
        return null;
    }
}
